package com.demo.service;

import com.demo.repository.UserRepository;
import mapper.RoleBean;
import mapper.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.faces.context.FacesContext;
import java.util.ArrayList;
import java.util.List;

/**
 * User: yuebo
 * Date: 13-8-29
 * Time: 下午10:09
 */
@Service
public class UserService implements UserDetailsService {

   public static final String SESSION_KEY="USER_SESSION";
   @Autowired
   private UserRepository userRepository ;

   public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
   }

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //Query searchUserQuery = new Query(Criteria.where("username").is(s));
        //UserBean userBean = operations.findOne(searchUserQuery,UserBean.class);
        UserBean userBean = userRepository.findByUsername(s);

        if(userBean==null)
            return null;

        List<SimpleGrantedAuthority> grantedAuthorityList = new ArrayList<SimpleGrantedAuthority>();
        for (RoleBean role:userBean.getRoles()){
            SimpleGrantedAuthority grantedAuthority=new SimpleGrantedAuthority(role.getRoleName());
            grantedAuthorityList.add(grantedAuthority);
        }

        User user=new User(userBean.getUsername(),userBean.getPassword(), grantedAuthorityList);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(SESSION_KEY,userBean);

        return user;
    }

    public static UserBean  getLoginUser(){
        return (UserBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(SESSION_KEY);
    }
}
